package JAVA;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.time.Period;
import java.util.Properties;

/**
 * @author wuyuecai
 * @create 2021/6/16
 */
public class ReflectionTest {
    @Test
    public void test(){
        Person person = new Person("张三", 18);
//        person.show();
        System.out.println(person);
    }
    @Test
    public void test2() throws Exception{
        Class<Person> pc = Person.class;
        System.out.println(pc);
        //1.通过反射创建person类的对象
        Constructor<Person> cons = pc.getConstructor(String.class, int.class);
        Object obj = cons.newInstance("tom", 20);
        Person p = (Person) obj;
        System.out.println(p);
        //通过反射调用对象的属性和方法
        Field age = pc.getDeclaredField("age");
        age.set(p, 23);
        System.out.println(p);

        Method show1 = pc.getDeclaredMethod("show");
        show1.setAccessible(true);
        show1.invoke(p);
        Method show = pc.getDeclaredMethod("showNation", String.class);
        show.setAccessible(true);
        Object invoke = show.invoke(p, "中国人");
        System.out.println(invoke);
        //        show.invoke(show);
//        Method show = pc.getDeclaredMethod("showNation", String.class);
//        show.invoke(show, "中国人");


    }
    @Test
    public void test3() throws ClassNotFoundException {
        Class<Person> aClass = Person.class;
        System.out.println(aClass);
        Person p = new Person();
        Class<Person> aClass1 = (Class<Person>) p.getClass();
        System.out.println(aClass1);
        Class<Person> aClass2 = (Class<Person>) Class.forName("JAVA.Person");
        System.out.println(aClass2);
    }
    @Test
    public void test4(){
        //类的加载器，用于加载字节码文件
        ClassLoader classLoader = ReflectionTest.class.getClassLoader();
        System.out.println(classLoader);
        ClassLoader classLoader1 = classLoader.getParent();
        System.out.println(classLoader1);
        ClassLoader parent = classLoader1.getParent();
        System.out.println(parent);
    }
    @Test
    public void test5() throws Exception {
        Properties properties = new Properties();
        //此时识别位置在当前的module下
        //读取配置文件方式一
//        FileInputStream fis = new FileInputStream("jdbc.properties");
//        properties.load(fis);
        //方式二使用类的加载器
//        此时是被位置在当前module的src下,写项目时配置文件一般写在src下，因为部署项目的时候module下的配置文件会丢失
        ClassLoader classLoader = ReflectionTest.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("jdbc1.properties");
        properties.load(is);
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        System.out.println("user="+user+",password="+password);
    }
}
